package cn.com.idmy.base.exception;

import cn.com.idmy.base.Err;
import lombok.Getter;
import lombok.experimental.Accessors;
import org.dromara.hutool.core.text.StrUtil;
import org.jetbrains.annotations.NotNull;

@Getter
@Accessors(fluent = true)
public class ErrorCodeException extends BizException {
    @NotNull
    protected final Err err;

    public ErrorCodeException processable(boolean processable) {
        this.processable = processable;
        return this;
    }

    public ErrorCodeException data(Object data) {
        this.data = data;
        return this;
    }

    public ErrorCodeException(@NotNull Err err) {
        super(err.code(), err.msg());
        this.err = err;
        this.data = null;
    }

    public ErrorCodeException(@NotNull Err err, @NotNull String msg, Object... params) {
        super(err.code(), buildMsg(err, msg, params));
        this.err = err;
        this.data = null;
    }

    public ErrorCodeException(@NotNull Throwable cause, @NotNull Err err) {
        super(cause, err.code(), err.msg());
        this.err = err;
        this.data = null;
    }

    public ErrorCodeException(@NotNull Throwable cause, @NotNull Err err, @NotNull String msg, Object... params) {
        super(cause, err.code(), buildMsg(err, msg, params));
        this.err = err;
        this.data = null;
    }

    protected static String buildMsg(@NotNull Err err, @NotNull String msg, Object... params) {
        if (StrUtil.contains(err.msg(), "【{}】")) {
            return StrUtil.format(err.msg(), msg, params);
        } else {
            return StrUtil.format(err.msg() + msg, params);
        }
    }
}
